<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 车辆月度费用台账详情 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rules">
      <a-spin :spinning="loading">
        <!-- 车辆基本信息 -->
        <a-card :bordered="false">
          <title-name title="车辆基本信息"></title-name>
          <custom-form :formList="baseForm" :form="form.carInfoVO || {}" editModel="V">
          </custom-form>
        </a-card>
        <!-- 费用 -->
        <a-card :bordered="false">
          <title-name title="费用"></title-name>
          <!-- 费用表单 -->
          <custom-form :formList="feeForm" :form="form" :editModel="editModel == 0 ? 'V' : ''">
            <template #cumulativeMileage>
              <a-input-number v-model="form.cumulativeMileage" v-if="editModel != 0" :min="0" :precision="2"
                @blur="blurCumulativeMileage" placeholder="请输入累计里程数（km）" />
              <span v-else>{{ form.cumulativeMileage || form.cumulativeMileage == 0 ? form.cumulativeMileage :
                  '无'
              }}</span>
            </template>
          </custom-form>
          <!-- 费用附件 -->
          <custom-form :formList="fileForm" :form="form" :editModel="editModel == 0 ? 'V' : ''">
            <!-- 附件上传 -->
            <template v-for="item in form.fileList" #[item.label]>
              <div :key="item.value" class="file_item">
                <template v-if="editModel != 0">
                  <l-table :fileAutoLoading="false" businessCode="OF12" :uploadArrys.sync="item.fileVOS"></l-table>
                </template>
                <file-link v-else :fileList="item.fileVOS"></file-link>
              </div>
            </template>
          </custom-form>
          <div v-if="editModel != 0" style="color: #999; padding-left: 130px">
            支持格式：.rar .zip .doc .docx .pdf .jpg...
          </div>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button :loading="loading" v-if="editModel != 0" type="primary" class="button_right" @click="handleSubmit">提交
        </a-button>
        <a-button type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components' // 表格
import { carMonthCost } from '@/api/office/vehicle/config' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
export default {
  name: 'monthlyAccountEdit',
  extends: new BaseEditPage(),
  components: {
    STable
  },
  data() {
    return {
      fileList: [
        { value: '0', label: '过桥/路费明细清单及发票' },
        { value: '1', label: '洗车费明细清单及发票' },
        { value: '2', label: '停车费明细清单及发票' },
        { value: '3', label: '检车费明细清单及发票' },
        { value: '4', label: '油费明细清单及发票' },
        { value: '5', label: '保险合同' },
        { value: '6', label: '其他' }
      ],
      loading: false, // 提交按钮loding
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        fileList: [
          { value: '0', label: '过桥/路费明细清单及发票' },
          { value: '1', label: '洗车费明细清单及发票' },
          { value: '2', label: '停车费明细清单及发票' },
          { value: '3', label: '检车费明细清单及发票' },
          { value: '4', label: '油费明细清单及发票' },
          { value: '5', label: '保险合同' },
          { value: '6', label: '其他' }
        ]
      }, // 表单
      rules: {
        cumulativeMileage: [{ required: true, message: '请输入累计里程数（km）', trigger: 'change' }],
      }
    }
  },
  mounted() {
    this.$route.meta.title = ['车辆月度费用台账查看', '车辆月度费用台账编辑'][this.editModel]
    // 不为添加时请求详情
    this.loading = true
    carMonthCost
      .detail({ id: this.id })
      .then((res) => {
        this.loading = false
        // 格式化文件
        if (!res.data.fileList || res.data.fileList.length === 0) {
          res.data.fileList = this.fileList
        }
        // 映射表单
        this.form = res.data
      })
      .catch(() => {
        this.loading = false
      })
  },
  computed: {
    // 车辆基本信息
    baseForm() {
      return [
        {
          keyName: 'unitName',
          label: '所属单位'
        },
        {
          keyName: 'carNatureName',
          label: '车辆性质'
        },
        {
          keyName: 'carNumber',
          label: '车牌号'
        },
        {
          keyName: 'brand',
          label: '品牌型号'
        },
        {
          keyName: 'carTypeName',
          label: '车辆类型'
        },
        {
          keyName: 'color',
          label: '车身颜色'
        },
        {
          keyName: 'engineNumber',
          label: '发动机号'
        },
        {
          keyName: 'gas',
          label: '排气量'
        },
        {
          keyName: 'chassisNumber',
          label: '车架号'
        },
        {
          keyName: 'forbid',
          label: '限行时间'
        },
        {
          keyName: 'stateName',
          label: '状态'
        },
        {
          keyName: 'driverName',
          label: '随车司机'
        },
        {
          keyName: 'auditTime',
          label: '年审日期'
        }
      ]
    },
    // 费用表单
    feeForm() {
      return [
        {
          keyName: 'month',
          type: 'BaseInput',
          disabled: true,
          label: '月份'
        },
        {
          keyName: 'roadCost',
          type: 'BaseInputNumber',
          precision: 2,
          label: '过路/桥费（元）',
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'washCost',
          type: 'BaseInputNumber',
          precision: 2,
          label: '洗车费（元）',
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'parkCost',
          type: 'BaseInputNumber',
          precision: 2,
          label: '停车费（元）',
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'checkCost',
          type: 'BaseInputNumber',
          precision: 2,
          label: '检车费（元）',
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'gasCost',
          type: 'BaseInputNumber',
          precision: 2,
          label: '油费（元）',
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'insuranceCost',
          type: 'BaseInputNumber',
          precision: 2,
          label: '保险费（元）',
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'cumulativeMileage',
          slot: true,
          label: '累计里程数（km）',
        },
        {
          keyName: 'nowMonthMileage',
          type: 'a-input-number',
          disabled: true,
          label: '当月里程数（km）',
        }
      ]
    },
    // 费用附件
    fileForm() {
      return this.form.fileList.map((item) => ({
        slot: true,
        keyName: item.label,
        label: item.label
      }))
    }
  },
  methods: {
    blurCumulativeMileage() {
      if (this.form.cumulativeMileage || this.form.cumulativeMileage === '0') {
        let params = {
          id: this.$route.query.id,
          cumulativeMileage: this.form.cumulativeMileage
        }
        carMonthCost
          .getLastMonthCarMonthCost(params)
          .then((res) => {
            if (res.code === '0') {
              this.form.nowMonthMileage = Object.keys(res.data).length ? res.data.nowMonthMileage : 0
            } else {
              this.$message.warning(res.msg || '请求失败')
            }
          })
          .catch(() => {
          })
      }
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          // 提交表单
          let form = that.$clone(that.form)
          // 格式化文件
          if (form.fileList?.length > 0) {
            let file = form.fileList.map((item) => {
              return {
                label: item.label,
                file: item.fileVOS?.map((i) => i.commonId)?.join()
              }
            }) // 文件参数
            form.file = file ? JSON.stringify(file) : void 0
            delete form.fileList
          }
          // 格式化金额
          that.feeForm.forEach((item, index) => {
            if (index !== 0 && !form[item.keyName]) {
              form[item.keyName] = 0
            }
          })
          // 提交表单
          that.loading = true
          carMonthCost
            .update(form)
            .then((res) => {
              that.loading = false;
              if (res.code === '0') {
                that.$message.success('提交成功！');
                that.$multiTab.close();
              } else {
                that.$message.warning(res.msg || '提交失败');
              }
            })
            .catch(() => {
              that.loading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.file_item {
  margin-top: -3px;
}

/deep/.ant-form-item {
  .ant-form-item-label {
    height: 28px;
    width: 200px;
    line-height: 22px;
    padding: 6px 4px 0 0;
    text-align: right;
    white-space: pre-wrap;
    overflow: visible;
  }

  .ant-form-item-control-wrapper {
    width: calc(100% - 200px);
  }
}
</style>